{% extends "admin/change_list.html" %}
{% load i18n admin_urls %}

{% block object-tools-items %}
    {{ block.super }}
    <li>
        <a href="{% url 'admin:rebuild_index' %}" class="addlink" id="rebuild-index-btn" onclick="return confirm('确定要重建文件索引吗？\n此操作会清空并重新扫描所有文件，耗时较长。')">重建文件索引</a>
    </li>
    {% if show_directory_management %}
    <li>
        <a href="#" onclick="showDirectoryManager(); return false;" class="addlink">
            目录管理
        </a>
    </li>
    {% endif %}
{% endblock %}

{% block extrahead %}
{{ block.super }}
<style>
.directory-manager {
    position: fixed;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    border: 2px solid #ccc;
    border-radius: 8px;
    padding: 20px;
    z-index: 1000;
    box-shadow: 0 4px 8 rgba(0,0,0,0.3);
    max-width: 500px;
    width: 90%;
}

.directory-manager h2 {
    margin-top: 0;
    color: #333;
}

.directory-manager input[type="text"] {
    width: 100%;
    padding:8px;
    margin: 10px 0;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.directory-manager button {
    margin: 5px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.directory-manager .btn-primary {
    background-color: #007bff;
    color: white;
}

.directory-manager .btn-secondary {
    background-color: #6c757d;
    color: white;
}

.directory-manager .btn-success {
    background-color: #28a745;
    color: white;
}

.overlay {
    position: fixed;
    top: 0;
    left:0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index:999
}
</style>

<script>
function showDirectoryManager() {
    const overlay = document.createElement('div');
    overlay.className = 'overlay';
    
    const manager = document.createElement('div');
    manager.className = 'directory-manager';
    manager.innerHTML = `
        <h2>目录管理</h2>
        <div>
            <label>创建新目录:</label>
            <input type="text" id="new_dir_path" placeholder="输入目录路径（支持多级，如：文档/2024/图片）">
            <button class="btn-success" onclick="createDirectory()">创建目录</button>
            <button class="btn-secondary" onclick="closeDirectoryManager()">关闭</button>
        </div>
        <div style="margin-top: 20px;">
            <label>现有目录:</label>
            <div id="directory_list" style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; margin-top: 10px;">
                加载中...
            </div>
            <button class="btn-primary" onclick="refreshDirectoryList()" style="margin-top: 10px;">刷新目录列表</button>
        </div>
    `;
    
    document.body.appendChild(overlay);
    document.body.appendChild(manager);
    
    // 加载目录列表
    refreshDirectoryList();
}

function closeDirectoryManager() {
    document.querySelector('.overlay').remove();
    document.querySelector('.directory-manager').remove();
}

function createDirectory() {
    const dirPath = document.getElementById('new_dir_path').value.trim();
    if (!dirPath) {
        alert('请输入目录路径');
        return;
    }
    
    const formData = new FormData();
    formData.append('dir_path', dirPath);

    fetch('/admin/file_manager/file/create_directory/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            document.getElementById('new_dir_path').value = '';
            refreshDirectoryList();
        } else {
            alert('创建目录失败: ' + data.error);
        }
    })
    .catch(error => {
        console.error('创建目录失败:', error);
        alert('创建目录失败，请重试');
    });
}

function refreshDirectoryList() {
    const listDiv = document.getElementById('directory_list');
    listDiv.innerHTML = '加载中...';
    
    fetch('/admin/file_manager/file/get_directories/')
        .then(response => response.json())
        .then(data => {
            if (data.directories && data.directories.length > 0) {
                const html = data.directories.map(dir => 
                    `<div style="padding: 5px; border-bottom:1px solid #eee;">${formatDirectoryName(dir)}</div>`
                ).join('');
                listDiv.innerHTML = html;
            } else {
                listDiv.innerHTML = '<div style="color: #666;">暂无目录</div>';
            }
        })
        .catch(error => {
            console.error('获取目录列表失败:', error);
            listDiv.innerHTML = '<div style="color: red;">获取目录列表失败</div>';
        });
}

function formatDirectoryName(dirPath) {
    const parts = dirPath.split('/');
    const indent = '　'.repeat(parts.length - 1); // 全角空格缩进
    return indent + parts[parts.length - 1];
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>
{% endblock %} 